<template>
  <div class="products-container">
    <!-- 数据管理模式切换 -->
    <el-tabs v-model="viewModeTab" class="view-mode-tabs">
      <el-tab-pane label="业务模式" name="business">
        <!-- 业务模式内容 -->
        <!-- 页面头部 -->
        <div class="page-header">
          <div class="header-left">
            <h1 class="page-title">产品管理</h1>
            <div class="status-badges">
              <el-tag type="primary" class="total-badge">
                <el-icon><Box /></el-icon>
                产品总数: {{ stats.totalProducts }}
              </el-tag>
              <el-tag type="success" class="active-badge">
                <el-icon><Goods /></el-icon>
                在售产品: {{ stats.activeProducts }}
              </el-tag>
              <el-tag type="warning" class="low-stock-badge">
                <el-icon><Warning /></el-icon>
                库存告急: {{ stats.lowStockProducts }}
              </el-tag>
            </div>
          </div>
          
          <div class="header-actions">
            <!-- 移除新增产品按钮，引导用户使用数据管理模式进行数据维护 -->
            <el-button 
              :icon="Refresh" 
              @click="loadProducts"
              :loading="loading"
            >
              刷新
            </el-button>
            
            <!-- 添加提示信息 -->
            <el-alert
              title="提示：如需进行产品数据维护（新增/编辑/删除），请使用下方的数据管理模式" 
              type="info"
              show-icon
              closable
              @close="handleTipClose"
              class="data-management-tip"
              v-if="showDataManagementTip"
            />
          </div>
        </div>

        <!-- 智能提醒 -->
        <div v-if="showSmartAlerts">
          <div class="smart-alerts-header">
            <span class="smart-alerts-title">智能提醒</span>
            <el-button link type="info" @click="closeSmartAlerts" class="close-btn">
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
          <ProductSmartAlerts 
            :products="products" 
            @alert-click="handleSmartAlertClick"
          />
        </div>

        <!-- 统计概览 -->
        <ProductStats :stats="stats" />

        <!-- 产品筛选 -->
        <ProductFilter 
          :query-params="queryParams"
          @search="handleSearch"
          @reset="handleReset"
        />

        <!-- 产品列表 -->
        <ProductTable
          :table-data="products"
          :loading="loading"
          :view-mode="viewMode"
          :pagination="pagination"
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          @sort-change="handleSort"
          @view-mode-toggle="toggleViewMode"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @show-detail="showProductDetail"
          @more-action="handleMoreAction"
        />

        <!-- 产品详情抽屉 -->
        <ProductDetailDrawer
          v-model="detailDrawerVisible"
          :product-id="currentProductId"
        />
      </el-tab-pane>
      <el-tab-pane label="数据管理模式" name="data">
        <!-- 数据管理模式内容 -->
        <!-- 页面标题 -->
        <PageHeader 
          title="产品管理" 
          description="管理您的产品信息，进行批量导入/导出、数据清洗等数据维护操作"
          icon="Goods"
        />
        
        <!-- 添加提示信息 -->
        <div class="data-management-tip" v-if="showDataManagementTip">
          <el-alert
            title="提示：此页面用于批量数据维护。如需进行日常业务操作，请切换到业务模式" 
            type="info"
            show-icon
            closable
            @close="handleTipClose"
          >
            <template #default>
              <div class="tip-content">
                <span>提示：此页面用于批量数据维护。如需进行日常业务操作，请前往</span>
                <el-link type="primary" @click="goToInventoryManagement">库存管理 → 产品管理</el-link>
              </div>
            </template>
          </el-alert>
        </div>
        
        <!-- 智能洞察 -->
        <SmartInsights 
          v-if="stats && Object.keys(stats).length > 0"
          :insights="smartInsights"
          @action="handleInsightAction"
        />
        
        <!-- 产品统计 -->
        <ProductStatsData 
          :stats="stats"
          :loading="loading"
        />
        
        <!-- 功能区域 -->
        <el-card class="function-area" shadow="never">
          <el-row :gutter="20">
            <el-col :span="16">
              <ProductFilterData 
                :query-params="queryParams"
                @search="handleSearch"
                @reset="handleReset"
              />
            </el-col>
            <el-col :span="8">
              <div class="function-buttons">
                <el-dropdown trigger="click" @command="handleBatchCommand">
                  <el-button class="batch-btn">
                    批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="export">导出产品</el-dropdown-item>
                      <el-dropdown-item command="import">导入产品</el-dropdown-item>
                      <el-dropdown-item command="delete" divided>删除产品</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </el-col>
          </el-row>
        </el-card>
        
        <!-- 产品表格 -->
        <ProductTableData
          :table-data="products"
          :loading="loading"
          :view-mode="'table'"
          :pagination="pagination"
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          @sort-change="handleSortChange"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @command="handleTableCommand"
        />
        
        <!-- 新增产品抽屉 -->
        <ProductEditDrawer
          v-model="addDrawerVisibleData"
          :mode="'create'"
          :product-data="null"
          @submit="createProduct"
          @close="handleAddDrawerClose"
        />
        
        <!-- 编辑产品抽屉 -->
        <ProductEditDrawer
          v-model="editDrawerVisibleData"
          :mode="'edit'"
          :product-data="editingProductData"
          @submit="updateProduct"
          @close="handleEditDrawerCloseData"
        />
        
        <!-- 产品详情抽屉 -->
        <ProductDetailDrawerData
          v-model="detailDrawerVisibleData"
          :product-id="detailProductData?.id || null"
          @edit="handleEditProductData"
          @close="handleDetailDrawerCloseData"
        />
        
        <!-- 产品导入向导 -->
        <ProductImportWizard
          v-model="importWizardVisibleData"
          :mode="'import'"
          :filter-params="queryParams"
          @import-success="handleImportSuccessData"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Box, Goods, Warning, Plus, Refresh, Close, ArrowDown
} from '@element-plus/icons-vue'

// 使用路由
const router = useRouter()

// 控制提示信息显示
const showDataManagementTip = ref(true)

// 控制智能提醒显示
const showSmartAlerts = ref(true)

// 视图模式
const viewModeTab = ref('business')

// 导入子组件
import ProductStats from './components/ProductStats.vue'
import ProductFilter from './components/ProductFilter.vue'
import ProductTable from './components/ProductTable.vue'
import ProductDetailDrawer from '@/components/inventory/ProductDetailDrawer.vue'
// 添加智能提醒组件
import ProductSmartAlerts from './components/ProductSmartAlerts.vue'

// 数据管理组件
import PageHeader from '@/components/layout/PageHeader.vue'
import SmartInsights from '@/components/insights/SmartInsights.vue'
import ProductStatsData from '@/views/inventory/components/ProductStats.vue'
import ProductFilterData from '@/views/inventory/components/ProductFilter.vue'
import ProductTableData from '@/views/inventory/components/ProductTable.vue'
import ProductEditDrawer from '@/components/inventory/ProductFormDialog.vue'
import ProductDetailDrawerData from '@/components/inventory/ProductDetailDrawer.vue'
import ProductImportWizard from '@/components/inventory/ProductImportExport.vue'

// 导入API模块
import * as inventoryAPI from '@/api/inventory'

// 跳转到库存管理
const goToInventoryManagement = () => {
  router.push('/inventory/products')
}

// 关闭提示信息
const handleTipClose = () => {
  showDataManagementTip.value = false
}

// 关闭智能提醒
const closeSmartAlerts = () => {
  showSmartAlerts.value = false
}

// 定义产品数据接口
interface Product {
  id: number
  sku: string
  name: string
  specification: string
  unit: string
  categoryId: number | null
  categoryName?: string
  brand: string
  brandId?: number | null
  brandName?: string
  description: string
  stock: number
  minStock: number
  salePrice: number
  costPrice: number
  status: string
  images: string[]
  createdAt: string
  updatedAt: string
}

interface ProductStats {
  totalProducts: number
  activeProducts: number
  lowStockProducts: number
  outOfStockProducts: number
  productTrend: number
  activeTrend: number
  lowStockTrend: number
}

interface ProductQueryParams {
  name: string
  sku: string
  categoryId: number | null
  brandId: number | null
  status: string
  minStock: number | null
  maxStock: number | null
  minPrice: number | null
  maxPrice: number | null
  createDateRange: string[]
  page: number
  limit: number
}

// 响应式数据
const products = ref<Product[]>([])
const loading = ref(false)
const detailDrawerVisible = ref(false)
const currentProductId = ref<number | null>(null)
const viewMode = ref<'table' | 'card'>('table')

// 数据管理模式的响应式数据
const addDrawerVisibleData = ref(false)
const editDrawerVisibleData = ref(false)
const detailDrawerVisibleData = ref(false)
const importWizardVisibleData = ref(false)
const detailProductData = ref<Product | null>(null)
const editingProductData = ref<Product | null>(null)
const selectedProductsData = ref<Product[]>([])

const stats = reactive<ProductStats>({
  totalProducts: 0,
  activeProducts: 0,
  lowStockProducts: 0,
  outOfStockProducts: 0,
  productTrend: 0,
  activeTrend: 0,
  lowStockTrend: 0
})

const smartInsights = ref([
  {
    id: '1',
    type: 'opportunity',
    title: '热销产品分析',
    description: '本月新增3个热销产品，库存周转率提升15%',
    priority: 'high',
    products: [],
    confidence: 85,
    action: () => ElMessage.info('查看热销产品详情')
  },
  {
    id: '2',
    type: 'risk',
    title: '库存风险预警',
    description: '5个产品库存不足，建议及时补货',
    priority: 'high',
    products: [],
    confidence: 78,
    action: () => ElMessage.info('查看库存风险产品')
  }
])

const queryParams = reactive<ProductQueryParams>({
  name: '',
  sku: '',
  categoryId: null,
  brandId: null,
  status: '',
  minStock: null,
  maxStock: null,
  minPrice: null,
  maxPrice: null,
  createDateRange: [],
  page: 1,
  limit: 20
})

const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 加载产品列表
const loadProducts = async () => {
  loading.value = true
  try {
    // 构造API查询参数
    const params = {
      name: queryParams.name || undefined,
      sku: queryParams.sku || undefined,
      category: queryParams.categoryId || undefined,
      status: queryParams.status || undefined,
      brand: queryParams.brandId || undefined,
      specification: queryParams.specification || undefined,
      minStock: queryParams.minStock,
      page: queryParams.page,
      limit: queryParams.limit
    }

    // 调用真实API
    const response = await inventoryAPI.getProducts(params)
    
    products.value = response.data.list
    pagination.total = response.data.pagination.total
    
    // 更新统计信息
    stats.totalProducts = response.data.stats.total
    stats.activeProducts = response.data.stats.active
    stats.lowStockProducts = response.data.stats.lowStock
  } catch (error) {
    console.error('加载产品列表失败:', error)
    ElMessage.error('加载产品列表失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

// 添加加载统计数据的方法
const loadProductStats = async () => {
  try {
    const response = await inventoryAPI.getProductStats()
    if (response.success) {
      Object.assign(stats, response.data)
    }
  } catch (error) {
    console.error('加载产品统计数据失败:', error)
    ElMessage.error('加载产品统计数据失败: ' + (error as Error).message)
  }
}

const showProductDetail = (product: Product) => {
  currentProductId.value = product.id
  detailDrawerVisible.value = true
}

const handleSearch = () => {
  queryParams.page = 1
  loadProducts()
}

const handleReset = () => {
  Object.assign(queryParams, {
    name: '',
    sku: '',
    categoryId: null,
    status: '',
    brandId: null,
    specification: '',
    minStock: null,
    createDateRange: [],
    page: 1,
    limit: 20
  })
  loadProducts()
}

const handleSelectionChange = (selection: Product[]) => {
  // 产品管理模块中不需要处理选择
}

const handleRowClick = (row: Product) => {
  // 可以显示快速详情
  console.log('点击产品:', row)
}

const handleMoreAction = (command: string, product: Product) => {
  switch (command) {
    case 'clone':
      cloneProduct(product)
      break
    case 'delete':
      deleteProduct(product)
      break
    default:
      ElMessage.warning('未知操作')
  }
}

// 复制产品
const cloneProduct = (product: Product) => {
  ElMessageBox.confirm(
    `确定要复制产品 "${product.name}" 吗？`,
    '确认复制',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      // 调用API复制产品
      const response = await inventoryAPI.cloneProduct(product.id)
      
      if (response.success) {
        ElMessage.success('产品复制成功')
        loadProducts() // 重新加载产品列表
      } else {
        ElMessage.error(response.message || '产品复制失败')
      }
    } catch (error) {
      console.error('复制产品失败:', error)
      ElMessage.error('产品复制失败: ' + (error as Error).message)
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 删除产品
const deleteProduct = (product: Product) => {
  ElMessageBox.confirm(
    `确定要删除产品 "${product.name}" 吗？此操作不可恢复！`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error',
    }
  ).then(async () => {
    try {
      // 调用API删除产品
      const response = await inventoryAPI.deleteProduct(product.id)
      
      if (response.success) {
        ElMessage.success('产品删除成功')
        loadProducts() // 重新加载产品列表
      } else {
        ElMessage.error(response.message || '产品删除失败')
      }
    } catch (error) {
      console.error('删除产品失败:', error)
      ElMessage.error('产品删除失败: ' + (error as Error).message)
    }
  }).catch(() => {
    // 用户取消操作
  })
}

const handleSort = (field: string) => {
  ElMessage.info(`按 ${field} 排序`)
  // 实际项目中应调用API进行排序
}

const toggleViewMode = () => {
  viewMode.value = viewMode.value === 'table' ? 'card' : 'table'
}

const handleSizeChange = (size: number) => {
  queryParams.limit = size
  queryParams.page = 1
  loadProducts()
}

const handleCurrentChange = (page: number) => {
  queryParams.page = page
  loadProducts()
}

// 添加处理智能提醒点击的方法
const handleSmartAlertClick = (alert: any) => {
  // 根据提醒类型进行相应处理
  switch (alert.type) {
    case 'low_stock':
      // 筛选库存告急的产品
      Object.assign(queryParams, {
        minStock: 0,
        maxStock: alert.threshold
      })
      handleSearch()
      ElMessage.success('已筛选显示库存告急的产品')
      break
    case 'out_of_stock':
      // 筛选缺货的产品
      Object.assign(queryParams, {
        status: 'out_of_stock'
      })
      handleSearch()
      ElMessage.success('已筛选显示缺货的产品')
      break
    case 'near_expiry':
      ElMessage.info('查看临期产品功能待实现')
      break
    default:
      ElMessage.info('暂不支持此操作')
  }
}

// 数据管理模式相关方法
const handleSortChange = (sort: { column: any, prop: string, order: string }) => {
  // 处理排序逻辑
  loadProducts()
}

const handleTableCommand = (command: { action: string, row: Product }) => {
  const { action, row } = command
  switch (action) {
    case 'detail':
      showDetailDrawerData(row)
      break
    case 'edit':
      showEditDrawerData(row)
      break
    case 'orders':
      viewProductOrdersData(row)
      break
    case 'delete':
      deleteProductData(row)
      break
  }
}

const showAddDrawerData = () => {
  addDrawerVisibleData.value = true
}

const showEditDrawerData = (product: Product) => {
  editingProductData.value = product
  editDrawerVisibleData.value = true
}

const showDetailDrawerData = (product: Product) => {
  detailProductData.value = product
  detailDrawerVisibleData.value = true
}

const handleEditProductData = (product: Product) => {
  detailDrawerVisibleData.value = false
  showEditDrawerData(product)
}

const viewProductOrdersData = (product: Product) => {
  // 跳转到产品订单页面
  ElMessage.info(`查看产品 ${product.name} 的订单`)
}

const deleteProductData = async (product: Product) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除产品 "${product.name}" 吗？此操作不可恢复。`,
      '删除确认',
      {
        type: 'warning'
      }
    )
    
    const response = await inventoryAPI.deleteProduct(product.id)
    if (response.success) {
      ElMessage.success('产品删除成功')
      loadProducts()
    } else {
      ElMessage.error(response.message || '删除产品失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除产品失败')
    }
  }
}

const createProduct = async (productData: Product) => {
  try {
    const response = await inventoryAPI.createProduct(productData)
    if (response.success) {
      ElMessage.success('产品创建成功')
      addDrawerVisibleData.value = false
      loadProducts()
      loadProductStats()
    } else {
      ElMessage.error(response.message || '创建产品失败')
    }
  } catch (error) {
    ElMessage.error('创建产品失败')
  }
}

const updateProduct = async (productData: Product) => {
  try {
    const response = await inventoryAPI.updateProduct(productData.id, productData)
    if (response.success) {
      ElMessage.success('产品更新成功')
      editDrawerVisibleData.value = false
      loadProducts()
    } else {
      ElMessage.error(response.message || '更新产品失败')
    }
  } catch (error) {
    ElMessage.error('更新产品失败')
  }
}

const handleBatchCommand = (command: string) => {
  switch (command) {
    case 'export':
      exportProductsData()
      break
    case 'import':
      importWizardVisibleData.value = true
      break
    case 'delete':
      batchDeleteProductsData()
      break
  }
}

const exportProductsData = () => {
  ElMessage.info('导出产品功能开发中')
}

const batchDeleteProductsData = async () => {
  if (selectedProductsData.value.length === 0) {
    ElMessage.warning('请先选择要删除的产品')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedProductsData.value.length} 个产品吗？此操作不可恢复。`,
      '批量删除确认',
      {
        type: 'warning'
      }
    )
    
    const ids = selectedProductsData.value.map(product => product.id)
    const response = await inventoryAPI.batchDeleteProducts(ids)
    if (response.success) {
      ElMessage.success('批量删除产品成功')
      loadProducts()
      loadProductStats()
    } else {
      ElMessage.error(response.message || '批量删除产品失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除产品失败')
    }
  }
}

const handleAddDrawerClose = () => {
  addDrawerVisibleData.value = false
}

const handleEditDrawerCloseData = () => {
  editDrawerVisibleData.value = false
  editingProductData.value = null
}

const handleDetailDrawerCloseData = () => {
  detailDrawerVisibleData.value = false
  detailProductData.value = null
}

const handleImportSuccessData = () => {
  importWizardVisibleData.value = false
  loadProducts()
  loadProductStats()
}

const handleInsightAction = (insight: any) => {
  insight.action()
}

// 生命周期钩子
onMounted(() => {
  loadProducts()
  loadProductStats()
})
</script>